import Taro from '@tarojs/taro';

interface FoodItem {
  id: string;
  name: string;
  category: string;
  quantity: number;
  unit: string;
  purchaseDate: string;
  expiryDate: string;
  status: 'normal' | 'low' | 'expiring';
  location?: string;
  image?: string;
}

const FOOD_LIST_KEY = 'kitchen_food_list';

export const getFoodList = (): FoodItem[] => {
  try {
    const data = Taro.getStorageSync(FOOD_LIST_KEY);
    if (data) {
      // 数据存在，返回解析后的数据
      return JSON.parse(data);
    }
  } catch (error) {
    console.error('读取食材列表失败:', error);
  }
  // 数据不存在或读取失败，返回空数组
  return [];
};

export const saveFoodList = (foodList: FoodItem[]): void => {
  try {
    const data = JSON.stringify(foodList);
    Taro.setStorageSync(FOOD_LIST_KEY, data);
  } catch (error) {
    console.error('保存食材列表失败:', error);
  }
};

export const addFood = (newFood: Omit<FoodItem, 'id' | 'purchaseDate' | 'status'>): FoodItem => {
  const newItem: FoodItem = {
    id: Date.now().toString(),
    name: newFood.name,
    category: newFood.category || '',
    quantity: newFood.quantity,
    unit: newFood.unit || '',
    purchaseDate: new Date().toISOString().split('T')[0],
    expiryDate: newFood.expiryDate || '',
    location: newFood.location || '',
    status: 'normal'
  };
  return newItem;
};

/**
 * 检查食材名称是否已存在
 * @param name 食材名称
 * @returns boolean 是否已存在
 */
export const checkFoodExists = (name: string): boolean => {
  try {
    const foodList = getFoodList();
    return foodList.some(item => item.name.toLowerCase().trim() === name.toLowerCase().trim());
  } catch (error) {
    console.error('检查食材是否存在失败:', error);
    return false;
  }
};

/**
 * 添加新食材到预设列表（用于用户自定义食材）
 * @param name 食材名称
 * @param category 食材分类
 * @returns boolean 添加是否成功
 */
export const addCustomFood = (name: string, category: string): { success: boolean; message: string } => {
  try {
    // 检查是否已存在
    if (checkFoodExists(name)) {
      return {
        success: false,
        message: `食材"${name}"已存在，请勿重复添加`
      };
    }

    // 这里可以将自定义食材保存到本地存储，供下次选择时使用
    const customFoodsKey = 'kitchen_custom_foods';
    let customFoods: Array<{ name: string; category: string; emoji: string }> = [];
    
    try {
      const data = Taro.getStorageSync(customFoodsKey);
      if (data) {
        customFoods = JSON.parse(data);
      }
    } catch (error) {
      console.error('读取自定义食材失败:', error);
    }

    // 检查自定义食材列表中是否已存在
    const exists = customFoods.some((food) => 
      food.name.toLowerCase().trim() === name.toLowerCase().trim()
    );

    if (!exists) {
      customFoods.push({
        name: name.trim(),
        category: category.trim(),
        emoji: category === '蔬菜' ? '🥬' : 
               category === '水果' ? '🍎' : 
               category === '肉类' ? '🥩' : 
               category === '主食' ? '🍚' : 
               category === '调料' ? '🧂' : 
               category === '蛋奶' ? '🥚' : '🍱'
      });

      // 保存到本地存储
      Taro.setStorageSync(customFoodsKey, JSON.stringify(customFoods));
    }

    return {
      success: true,
      message: `成功添加新食材"${name}"`
    };
  } catch (error) {
    console.error('添加自定义食材失败:', error);
    return {
      success: false,
      message: '添加失败，请重试'
    };
  }
};

/**
 * 获取自定义食材列表
 * @returns 自定义食材数组
 */
export const getCustomFoods = (): Array<{ name: string; category: string; emoji: string }> => {
  try {
    const customFoodsKey = 'kitchen_custom_foods';
    const data = Taro.getStorageSync(customFoodsKey);
    if (data) {
      return JSON.parse(data);
    }
  } catch (error) {
    console.error('读取自定义食材失败:', error);
  }
  return [];
};

/**
 * 根据过期日期计算食材状态
 * @param expiryDate 过期日期 (YYYY-MM-DD)
 * @returns 状态 'normal' | 'low' | 'expiring'
 */
export const calculateStatus = (expiryDate: string): 'normal' | 'low' | 'expiring' => {
  // 如果没有过期日期，返回正常状态
  if (!expiryDate || expiryDate.trim() === '') {
    return 'normal';
  }

  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const expiry = new Date(expiryDate);
  
  // 检查日期是否有效
  if (isNaN(expiry.getTime())) {
    return 'normal';
  }
  
  expiry.setHours(0, 0, 0, 0);
  const diffTime = expiry.getTime() - today.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays < 0) {
    return 'expiring'; // 已过期
  } else if (diffDays <= 3) {
    return 'expiring'; // 3天内过期
  } else if (diffDays <= 7) {
    return 'low'; // 7天内过期
  } else {
    return 'normal'; // 正常
  }
};

/**
 * 导出食材数据为JSON文件
 * @returns Promise<void>
 */
export const exportFoodData = async (): Promise<void> => {
  try {
    const foodList = getFoodList();
    if (foodList.length === 0) {
      Taro.showToast({
        title: '暂无食材数据可导出',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 创建导出数据对象
    const exportData = {
      version: '1.0',
      exportTime: new Date().toISOString(),
      appName: '厨房助手',
      foodList: foodList
    };

    const jsonString = JSON.stringify(exportData, null, 2);
    const fileName = `厨房助手_食材数据_${new Date().toISOString().split('T')[0]}.json`;

    // 在微信小程序中，我们使用临时文件的方式
    const fs = Taro.getFileSystemManager();
    const filePath = `${Taro.env.USER_DATA_PATH}/${fileName}`;

    // 写入文件
    fs.writeFileSync(filePath, jsonString, 'utf8');

    // 分享文件
    await Taro.shareFileMessage({
      filePath: filePath,
      fileName: fileName
    });

    Taro.showToast({
      title: '导出成功',
      icon: 'success',
      duration: 2000
    });

  } catch (error) {
    console.error('导出食材数据失败:', error);
    Taro.showToast({
      title: '导出失败，请重试',
      icon: 'none',
      duration: 2000
    });
  }
};

/**
 * 导入食材数据
 * @returns Promise<boolean> 导入是否成功
 */
export const importFoodData = async (): Promise<boolean> => {
  try {
    // 选择文件
    const result = await Taro.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['json']
    });

    if (!result.tempFiles || result.tempFiles.length === 0) {
      return false;
    }

    const file = result.tempFiles[0];
    const fs = Taro.getFileSystemManager();

    // 读取文件内容
    const fileContent = fs.readFileSync(file.path, 'utf8') as string;
    const importData = JSON.parse(fileContent);

    // 验证数据格式
    if (!importData.foodList || !Array.isArray(importData.foodList)) {
      Taro.showToast({
        title: '文件格式不正确',
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    // 验证食材数据结构 - 只验证必需字段，允许可选字段为空
    const isValidFoodList = importData.foodList.every((item: any) => {
      return item.id && 
             item.name && 
             item.category && 
             typeof item.quantity === 'number' && 
             item.hasOwnProperty('unit') && 
             item.purchaseDate && 
             item.hasOwnProperty('expiryDate');
    });

    if (!isValidFoodList) {
      Taro.showToast({
        title: '食材数据格式不正确',
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    // 询问用户是否覆盖现有数据
    const currentFoodList = getFoodList();
    let shouldImport = true;

    if (currentFoodList.length > 0) {
      const res = await Taro.showModal({
        title: '导入确认',
        content: `当前已有 ${currentFoodList.length} 种食材，导入将会覆盖现有数据。是否继续？`,
        confirmText: '覆盖导入',
        cancelText: '取消'
      });
      shouldImport = res.confirm;
    }

    if (!shouldImport) {
      return false;
    }

    // 更新食材状态
    const updatedFoodList = importData.foodList.map((item: FoodItem) => ({
      ...item,
      status: calculateStatus(item.expiryDate)
    }));

    // 保存数据
    saveFoodList(updatedFoodList);

    Taro.showToast({
      title: `成功导入 ${updatedFoodList.length} 种食材`,
      icon: 'success',
      duration: 2000
    });

    return true;

  } catch (error) {
    console.error('导入食材数据失败:', error);
    Taro.showToast({
      title: '导入失败，请检查文件格式',
      icon: 'none',
      duration: 2000
    });
    return false;
  }
};

/**
 * 更新食材信息
 * @param id 食材ID
 * @param updatedFood 更新的食材信息
 * @returns boolean 更新是否成功
 */
export const updateFood = (id: string, updatedFood: Partial<FoodItem>): boolean => {
  try {
    const foodList = getFoodList();
    const index = foodList.findIndex(item => item.id === id);
    
    if (index === -1) {
      console.error('未找到要更新的食材:', id);
      return false;
    }

    // 更新食材信息
    const updatedItem: FoodItem = {
      ...foodList[index],
      ...updatedFood,
      // 重新计算状态
      status: calculateStatus(updatedFood.expiryDate || foodList[index].expiryDate)
    };

    foodList[index] = updatedItem;
    saveFoodList(foodList);
    
    return true;
  } catch (error) {
    console.error('更新食材失败:', error);
    return false;
  }
};

/**
 * 删除食材
 * @param id 食材ID
 * @returns boolean 删除是否成功
 */
export const deleteFood = (id: string): boolean => {
  try {
    const foodList = getFoodList();
    const filteredList = foodList.filter(item => item.id !== id);
    
    if (filteredList.length === foodList.length) {
      console.error('未找到要删除的食材:', id);
      return false;
    }

    saveFoodList(filteredList);
    return true;
  } catch (error) {
    console.error('删除食材失败:', error);
    return false;
  }
};

/**
 * 批量删除食材
 * @param ids 食材ID数组
 * @returns boolean 删除是否成功
 */
export const deleteFoodBatch = (ids: string[]): boolean => {
  try {
    const foodList = getFoodList();
    const filteredList = foodList.filter(item => !ids.includes(item.id));
    
    saveFoodList(filteredList);
    return true;
  } catch (error) {
    console.error('批量删除食材失败:', error);
    return false;
  }
};

/**
 * 删除所有食材
 * @returns boolean 删除是否成功
 */
export const deleteAllFood = (): boolean => {
  try {
    saveFoodList([]);
    return true;
  } catch (error) {
    console.error('删除所有食材失败:', error);
    return false;
  }
};
